from fileOperate import loadFromFileRaw, writeToFileRaw
import json

class Config():
    _path = "" # eg: /home/Zecyel/config.json
    _mp = {}
    autoSave = False
    makeBackup = False
    # Warning: autoSave = makeBackup = True may cause low-running-speed

    def __init__(self, path = None):
        self._path = path

    def load(self, path):
        self._path = path
        stt, tmp = loadFromFileRaw(path)
        assert stt
        self._mp = json.loads(tmp)

    def __setitem__(self, key, value):
        self._mp[key] = value
        if self.autoSave:
            self.save()

    def __getitem__(self, key):
        return self._mp[key]
        
    def save(self):
        pos = self._path.rindex("/") + 1
        binDir = self._path[:pos]
        posDot = self._path.rindex(".")
        filename = self._path[pos: posDot]
        post = self._path[posDot + 1:]
        if self.makeBackup:
            moveFile(self._path, binDir + "backup/" + filename + "." + timeStamp() + "." + post)
        writeToFileRaw(self._path, json.dumps(self._mp, indent = 4)) # indent 为了好看一点
